import React, { Component, useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Form } from 'antd';
import { apiGetPlatformSetList, apiGetPlatformSetEdit } from '@/request/configuration'
import '../style/index.less'
import { parseJson } from '@/utils/toJSON';

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={parseJson(record.rules)}
      >
        <Input ref={inputRef} onPressEnter={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

class PlatformSet extends Component {
  formRef = React.createRef()
  inputRef = React.createRef()
  state = {
    loading: false,
    dataSource: [],
    columns: [
      {
        title: '配置项',
        dataIndex: "storePlatformSetKey",
        key: "storePlatformSetKey",
        align: 'center',
        width: '50%',
      },
      {
        title: '值',
        dataIndex: "storePlatformSetShowValue",
        key: "storePlatformSetShowValue",
        align: 'center',
        editable: true,
        render: (text, record) => {
          return <div>
            {record.storePlatformSetShowValue + record.storePlatformSetUnit}
          </div>
        },
        width: '50%'
      },
    ],
    editIndex: null,
    editValue: ''
  }

  async componentDidMount() {
    await this.getData()
  }

  getData = async () => {
    const response = await apiGetPlatformSetList()
    if (response.code === 0) {
      const arr = response.data.filter(v => v.storePlatformSetShow === 'Y')
      this.setState({
        dataSource: arr
      })
    }
  }

  handleSave = async (row) => {
    let res = await apiGetPlatformSetEdit({ storePlatformSetId: row.storePlatformSetId, storePlatformSetShowValue: row.storePlatformSetShowValue })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.getData()
    }
  }
  render() {
    const { loading, dataSource } = this.state
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.state.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return <div className={"p-layout-box configuration"}>
      <div className={'platform-set-list'}>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          loading={loading}
          pagination={false}
          {...this.props}
        />
      </div>
    </div>
  }
}

export default PlatformSet